<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { type EChartsOption } from 'echarts'
import type { CustomerSales, SaleInfoParam } from '@/api/dashboard/types'
import { getAnnualSalesByCustomer } from '@/api/dashboard/dashboard'
import { useResponsiveBarForCustomers } from '@/h5/useEchartsOption/useEchartsOption'
import '@/h5/analysis.css'

const props = defineProps<{ yearId: number; customerId?: number }>()

const loading = ref(false)
const chartData = reactive<CustomerSales[]>([
  { name: '全部', amount: 0, quantity: 0 },
])

const formModel = reactive<SaleInfoParam>({
  yearId: props.yearId ?? 2024,
  customerId: props.customerId ?? 0,
})

function setChartData(data: CustomerSales[]) {
  chartData.splice(0, chartData.length, ...data)
}

async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    console.log('年度销售客户组件 - 开始调用 API，参数:', { 
      customerId: props.customerId, 
      yearId: props.yearId 
    })
    const res = await getAnnualSalesByCustomer({ 
      customerId: props.customerId,
      yearId: props.yearId 
    })
    console.log('年度销售客户组件 - API 调用成功，返回数据:', res)
    const incoming = Array.isArray((res as any)?.data) ? (res as any).data : []
    console.log('年度销售客户组件 - 解析后的数据条数:', incoming.length)
    // 打印前5条数据做快速检查
    console.log('年度销售客户组件 - 示例数据前5条:', incoming.slice(0, 5))
    setChartData(incoming)
    console.log('年度销售客户组件 - 设置到图表后的数据条数:', chartData.length)
  }
  catch (error) {
    console.error('年度销售客户组件 - API 调用失败:', error)
  }
  finally {
    loading.value = false
  }
}

watch(() => [props.yearId, props.customerId], ([y, c]) => {
  formModel.yearId = y ?? 2024
  formModel.customerId = c ?? 0
  init()
})

onMounted(() => {
  init()
})

const option = computed<EChartsOption>(() => {
  const opt = useResponsiveBarForCustomers(chartData)
  // 打印关键的维度与数值数组长度，便于确认是否为空/不匹配
  try {
    const categories = chartData.map(d => d.name)
    const amounts = chartData.map(d => d.amount ?? 0)
    const quantities = chartData.map(d => d.quantity ?? 0)
    console.log('年度销售客户组件 - 图表维度与数据长度:', { categories: categories.length, amounts: amounts.length, quantities: quantities.length })
  } catch (e) {
    console.warn('年度销售客户组件 - 图表数据统计失败:', e)
  }
  return opt
})

const isEmpty = computed(() => {
  // 放宽空数据判断：只在没有任何数据项时显示空提示。
  // 即使金额与斤数都为0，也渲染坐标与柱体，避免误判为“未加载”。
  return !chartData.length
})
</script>

<template>
  <div class="h5-analysis-block">
    <div class="chart-title">年度客户销售统计</div>
    <div class="chart-container">
      <template v-if="!isEmpty">
        <Chart :option="option" :loading="loading" height="auto" />
      </template>
      <template v-else>
        <div class="chart-empty">
          <a-empty description="暂无数据" />
        </div>
      </template>
    </div>
  </div>
</template>

<!-- 移除局部样式，使用全局 analysis.css -->